package com.wing.device.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.annotation.RequestObjectFieldIgnore;
import com.wing.common.enums.InspectEnum;
import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.device.model.entity.*;
import com.wing.device.model.response.DeviceInspectVO;
import com.wing.device.model.response.MaintenanExecuteDetailVo;
import com.wing.device.model.response.MaintenanceVo;
import com.wing.device.service.*;
import com.wing.web.db.config.util.DynamicDataSource;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @version 1.1.0
 * @Author hz
 * @Date 2024-08-19 15:13
 **/
@Validated
@Api(value = "Admin-设备维修任务管理", tags = "#/device/inspect")
@RestController("inspectController")
@RequestMapping("device/admin/inspect")
@Slf4j
public class DeviceInspectController {

    @Resource
    private DeviceInspectService deviceInspectService;

    @Resource
    private DeviceInspectClaimService deviceInspectClaimService;

    @Resource
    private DeviceInspectExecuteService deviceInspectExecuteService;


    @ApiOperation(value = "查询设备年检任务列表", notes = "搜索")
    @GetMapping("/list")
    public PageResult<DeviceInspectVO> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(defaultValue = "create_time") String sort,
            @RequestParam(defaultValue = "asc") String order,
            String deviceType,
            String inspectStatus,
            String id,
            String deviceId,
            String taskNo
            ){
        Page<DeviceInspect> pg = new Page<>(page, limit);
        Map map = new HashMap();
        map.put("deviceType", deviceType);
        map.put("inspectStatus", inspectStatus);
        map.put("id", id);
        map.put(taskNo, taskNo);
        map.put("deviceId", deviceId);
        String databaseUser = DynamicDataSource.USER_PREFIX;
        if (StringUtils.isNotBlank(DynamicDataSource.name.get())) {
            databaseUser = databaseUser + "-" + DynamicDataSource.name.get();
        }
        map.put("databaseUser", databaseUser);
        IPage<DeviceInspectVO> list = deviceInspectService.pageList4app(pg, map);
        //关联相关业务属性
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "添加年检任务", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@RequestBody DeviceInspect deviceInspect) {
        try {
            if (null == deviceInspect.getModifier()){
                deviceInspect.setModifier(JwtUtils.getLoginUserId());
                deviceInspect.setModifierName(JwtUtils.getLoginUsername());
                deviceInspect.setUpdateTime(LocalDateTime.now());
            }
            if (null == deviceInspect.getCreator()){
                deviceInspect.setCreator(JwtUtils.getLoginUserId());
                deviceInspect.setCreatorName(JwtUtils.getLoginUsername());
                deviceInspect.setCreateTime(LocalDateTime.now());
            }
            deviceInspect.setInspectStatus(InspectEnum.InspectStatusEnum.DRL.getCode());
            deviceInspectService.save(deviceInspect);
            return JsonResult.success("添加成功");
        } catch (Exception e) {
            log.error("添加失败:", e);
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "修改年检任务", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@RequestBody DeviceInspect deviceInspect) {
        try {
            DeviceInspect type = deviceInspectService.getById(deviceInspect.getId());
            if (ObjectUtil.isEmpty(type)){
                return JsonResult.fail("无效id！");
            }
            CopyOptions copyOptions = CopyOptions.create()
                    .setEditable(DeviceInspect.class)
                    .setIgnoreError(true)
                    .setIgnoreNullValue(true);
            BeanUtil.copyProperties(deviceInspect, type, copyOptions);
            deviceInspectService.updateById(type);
            return JsonResult.success("修改成功！");
        } catch (Exception e) {
            return JsonResult.fail("修改失败:" + e.getMessage());
        }
    }

    @ApiOperation(value = "删除年检任务", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "设备表id", required = true, dataType = "Long", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long deviceId) {

        if (deviceInspectService.removeById(deviceId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    /**
     * 认领任务
     * @param id 维保主键id
     * @return
     */
    @ApiOperation(value = "认领维保任务", notes = "认领")
    @PostMapping("/claim")
    @Transactional(rollbackFor = Exception.class)
    public JsonResult claim(Long id) {
        try {
            DeviceInspect type = deviceInspectService.getById(id);
            if (ObjectUtil.isEmpty(type)){
                return JsonResult.fail("无效id！");
            }
            //如果不是
            if (!type.getInspectStatus().equals(InspectEnum.InspectStatusEnum.DRL.getCode())){
                return JsonResult.fail("该任务已经被认领！");
            }
            type.setInspectStatus(InspectEnum.InspectStatusEnum.YRL.getCode());
            deviceInspectService.updateById(type);
            //创建认领记录
            DeviceInspectClaim claim = new DeviceInspectClaim();
            claim.setClaimNo(UniqueIdGeneratorUtil.generateUniqueId("NJRL", "yyyyMMdd", 1000, 9999));
            claim.setInspectId(id);
            claim.setCreateTime(LocalDateTime.now());
            claim.setCreator(JwtUtils.getLoginUserId());
            claim.setCreatorName(JwtUtils.getLoginUsername());
            deviceInspectClaimService.save(claim);
            return JsonResult.success("认领成功！");
        } catch (Exception e) {
            return JsonResult.fail("认领失败:" + e.getMessage());
        }
    }

}
